package com.sumer.psychology.blog.application.command;

import com.sumer.psychology.blog.domain.model.Category;
import com.sumer.psychology.blog.domain.model.CategoryId;
import com.sumer.psychology.blog.domain.model.CategoryRepository;
import com.sumer.psychology.common.Assert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 目录服务
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/9/3
 * Time: 9:00
 */
@Transactional
public class CategoryApplicationService {
    private CategoryRepository categoryRepository;

    public CategoryApplicationService(CategoryRepository categoryRepository) {
        this.categoryRepository = categoryRepository;
    }

    /**
     * 创建目录
     *
     * @param createCategoryCommand command
     */
    public CategoryId newCategory(CreateCategoryCommand createCategoryCommand) {
        Category aCategory = new Category(
                categoryRepository().nextIdentity(),
                createCategoryCommand.author(),
                createCategoryCommand.categoryName());

        categoryRepository().add(aCategory);

        return aCategory.categoryId();
    }

    /**
     * 重命名
     *
     * @param renameCategoryCommand command
     */
    public void rename(RenameCategoryCommand renameCategoryCommand) {
        Category aCategory = categoryRepository().activeCategoryOfId(
                new CategoryId(renameCategoryCommand.categoryId()));

        Assert.notNull(aCategory, "目录不能为空");

        aCategory.changeName(renameCategoryCommand.changedName());
    }

    /**
     * 删除目录
     *
     * @param deleteCategoryCommand command
     */
    public void delete(DeleteCategoryCommand deleteCategoryCommand) {
        Category deletedCategory = categoryRepository().activeCategoryOfId(
                new CategoryId(deleteCategoryCommand.deletedId()));

        if (deletedCategory != null) {
            deletedCategory.delete();
        }
    }

    public CategoryRepository categoryRepository() {
        return categoryRepository;
    }

}
